package chapter05_string;

import com.sun.deploy.panel.ITreeNode;

import java.security.cert.TrustAnchor;

/**
 * 描述：字符串中数字子串求和
 *
 * @author hl
 * @date 2021/8/8 9:24
 */
public class NumSum {
    public static void main(String[] args) {
        NumSum main = new NumSum();
        String str1 = "A1CD2E33";
        String str2 = "A-1B--2--1D6E";
        int sum1 = main.numSum(str1);
        int sum2 = main.numSum(str2);
        System.out.println(sum1);
        System.out.println(sum2);
    }
    public int numSum(String str){
        if (str == null || str.length() == 0) {
            return 0;
        }
        int res = 0;
        int num = 0;
        boolean posi = true;
        int cur = 0;
        for (int i = 0; i < str.length(); i++) {
            cur = str.charAt(i) - '0';
            if (cur < 0 || cur > 9) {
                res += num;
                num = 0;
                if (str.charAt(i) == '-') {
                    if (i - 1 >= 0 && str.charAt(i - 1) == '-') {
                        posi = !posi;
                    }else{
                        posi = false;
                    }
                }else {
                    posi = true;
                }
            }else{
                num = num * 10 + (posi ? cur : -cur);
            }
        }
        res += num;
        return res;
    }
}
